Online-Academy
Look, Read, Understand, Apply

Java Generics

Generics introduce type parameters to Java code. For example:

List<String> names = new ArrayList<>();

Here, String is the type parameter for the generic class List<T>. The T is a placeholder that gets replaced with a real type (like String, Integer, etc.) when the code is compiled.
Generics are important because:
  • Type safety - Catch type errors at compile time.
  • Code reusability - Write a method/class once and use it for different types.
  • Elimination of casts - No need to manually cast when retrieving objects.
  • Cleaner code - More readable and maintainable.
    class Gen<T>{
	T val;
	Gen(T v){
		val = v;
	}
	T getVal(){
		return val;
	}
	void showType(){
		System.out.println("Type: "+val.getClass().getName());
	}
}
Bounded Generics, here T is of type Number

Here, Generics class can of any Number type like: Integer, Float, Double, Long etc.

class Gen_ii<T extends Number>{ T[] val; Gen_ii(T[] values){ val = values; } void sum(){ double sum = 0; for(int i=0;i<val.length;i++) sum += val[i].doubleValue(); System.out.println("Sum: "+sum); } } class Generics_demo{ public static void main(String[] arrgs){ Gen<Integer> g = new Gen<Integer>(77); int x = g.getVal(); System.out.println("x: "+x); g.showType(); Integer[] list = {1,2,3,4,5,6,7,8,9,10}; Gen_ii<Integer> gg = new Gen_ii<Integer>(list); gg.sum(); Double[] dlist = {1.2,2.4,4.5}; Gen_ii<Double> dg = new Gen_ii<Double>(dlist); dg.sum(); } }